const authController = require('../controllers/authController');
const { authenticate, optionalAuthenticate } = require('../middleware/auth');
const { identifyTenant, requireTenant } = require('../middleware/tenant');

async function authRoutes(fastify, options) {
  // 应用租户识别中间件到所有路由
  fastify.addHook('preHandler', identifyTenant);
  
  // 公开路由 - 不需要认证
  
  // 用户注册
  fastify.post('/register', {
    preHandler: [requireTenant],
    schema: {
      description: 'Register a new user',
      tags: ['Authentication'],
      body: {
        type: 'object',
        required: ['email', 'password', 'firstName', 'lastName'],
        properties: {
          email: { 
            type: 'string', 
            format: 'email',
            description: 'User email address'
          },
          password: { 
            type: 'string', 
            minLength: 8,
            description: 'User password (minimum 8 characters)'
          },
          firstName: { 
            type: 'string', 
            minLength: 1, 
            maxLength: 50,
            description: 'User first name'
          },
          lastName: { 
            type: 'string', 
            minLength: 1, 
            maxLength: 50,
            description: 'User last name'
          },
          role: { 
            type: 'string', 
            enum: ['admin', 'user'],
            default: 'user',
            description: 'User role'
          }
        }
      },
      response: {
        201: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                user: {
                  type: 'object',
                  properties: {
                    id: { type: 'string' },
                    email: { type: 'string' },
                    firstName: { type: 'string' },
                    lastName: { type: 'string' },
                    role: { type: 'string' }
                  }
                }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.register);
  
  // 用户登录
  fastify.post('/login', {
    preHandler: [requireTenant],
    schema: {
      description: 'User login',
      tags: ['Authentication'],
      body: {
        type: 'object',
        required: ['email', 'password'],
        properties: {
          email: { 
            type: 'string', 
            format: 'email',
            description: 'User email address'
          },
          password: { 
            type: 'string',
            description: 'User password'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                user: {
                  type: 'object',
                  properties: {
                    id: { type: 'string' },
                    email: { type: 'string' },
                    firstName: { type: 'string' },
                    lastName: { type: 'string' },
                    role: { type: 'string' }
                  }
                },
                accessToken: { type: 'string' },
                expiresIn: { type: 'number' }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.login);
  
  // 刷新访问令牌
  fastify.post('/refresh-token', {
    schema: {
      description: 'Refresh access token',
      tags: ['Authentication'],
      body: {
        type: 'object',
        properties: {
          refreshToken: { 
            type: 'string',
            description: 'Refresh token (optional if provided via cookie)'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                accessToken: { type: 'string' },
                expiresIn: { type: 'number' }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.refreshToken);
  
  // 验证邮箱
  fastify.post('/verify-email', {
    schema: {
      description: 'Verify user email address',
      tags: ['Authentication'],
      body: {
        type: 'object',
        required: ['token'],
        properties: {
          token: { 
            type: 'string',
            description: 'Email verification token'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.verifyEmail);
  
  // 忘记密码
  fastify.post('/forgot-password', {
    preHandler: [requireTenant],
    schema: {
      description: 'Request password reset',
      tags: ['Authentication'],
      body: {
        type: 'object',
        required: ['email'],
        properties: {
          email: { 
            type: 'string', 
            format: 'email',
            description: 'User email address'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.forgotPassword);
  
  // 重置密码
  fastify.post('/reset-password', {
    schema: {
      description: 'Reset user password',
      tags: ['Authentication'],
      body: {
        type: 'object',
        required: ['token', 'password'],
        properties: {
          token: { 
            type: 'string',
            description: 'Password reset token'
          },
          password: { 
            type: 'string', 
            minLength: 8,
            description: 'New password (minimum 8 characters)'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.resetPassword);
  
  // 重新发送验证邮件
  fastify.post('/resend-verification', {
    preHandler: [requireTenant],
    schema: {
      description: 'Resend email verification',
      tags: ['Authentication'],
      body: {
        type: 'object',
        required: ['email'],
        properties: {
          email: { 
            type: 'string', 
            format: 'email',
            description: 'User email address'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.resendVerificationEmail);
  
  // 验证令牌
  fastify.post('/validate-token', {
    schema: {
      description: 'Validate access token',
      tags: ['Authentication'],
      headers: {
        type: 'object',
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                valid: { type: 'boolean' },
                user: {
                  type: 'object',
                  properties: {
                    id: { type: 'string' },
                    email: { type: 'string' },
                    role: { type: 'string' },
                    tenantId: { type: 'string' }
                  }
                }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.validateToken);
  
  // 受保护的路由 - 需要认证
  
  // 获取当前用户信息
  fastify.get('/profile', {
    preHandler: [authenticate],
    schema: {
      description: 'Get current user profile',
      tags: ['Authentication'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            data: {
              type: 'object',
              properties: {
                user: {
                  type: 'object',
                  properties: {
                    id: { type: 'string' },
                    email: { type: 'string' },
                    firstName: { type: 'string' },
                    lastName: { type: 'string' },
                    role: { type: 'string' },
                    tenantId: { type: 'string' },
                    lastLogin: { type: 'string' }
                  }
                }
              }
            },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.getProfile);
  
  // 修改密码
  fastify.post('/change-password', {
    preHandler: [authenticate],
    schema: {
      description: 'Change user password',
      tags: ['Authentication'],
      headers: {
        type: 'object',
        required: ['authorization'],
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token'
          }
        }
      },
      body: {
        type: 'object',
        required: ['currentPassword', 'newPassword'],
        properties: {
          currentPassword: { 
            type: 'string',
            description: 'Current password'
          },
          newPassword: { 
            type: 'string', 
            minLength: 8,
            description: 'New password (minimum 8 characters)'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.changePassword);
  
  // 登出
  fastify.post('/logout', {
    preHandler: [optionalAuthenticate],
    schema: {
      description: 'User logout',
      tags: ['Authentication'],
      headers: {
        type: 'object',
        properties: {
          authorization: { 
            type: 'string',
            description: 'Bearer token (optional)'
          }
        }
      },
      response: {
        200: {
          type: 'object',
          properties: {
            success: { type: 'boolean' },
            message: { type: 'string' }
          }
        }
      }
    }
  }, authController.logout);
}

module.exports = authRoutes;